import React, { useEffect, useState } from 'react'
import { message, Upload } from 'antd'
import { ossConfig } from '@/services/common'

const FileUpload = (props) => {
  // 把服务器传过来的api放进状态
  const [ossData, setOssData] = useState({})

  /**
   * 初始化 获取oss上传签名
   * @returns {Promise<void>}
   */
  useEffect(async () => {
    const ossData = await ossConfig()

    ossData.host = ossData.host.replace('http', 'https')
    setOssData(ossData)
    if (props.onHandle !== undefined && props.url !== undefined) {
      props.onHandle(ossData.host + props.url)
    }
  }, [])

  /**
   *  文件上传过程中的回调函数 直到上传完成
   * @param fileList
   */
  const onChange = ({ file }) => {

    if (file.status === 'done') {

      // props.setLogoKey(file.key)
      const { setUrlKey } = props

      // 上传成功之后, 把文件的key, 设置为表单某个字段的值
      if (setUrlKey) setUrlKey(file.key)

      message.success('上传成功')
    }
  }
  /**
   * 额外的上传参数
   * @param file
   * @returns {{OSSAccessKeyId: string, Signature: *, key, policy: (string|Protocol.Emulation.VirtualTimePolicy|*)}}
   */
  const getExtraData = file => {
    return {
      key: file.url,
      OSSAccessKeyId: ossData.accessid,
      policy: ossData.policy,
      Signature: ossData.signature,
    }
  }

  /**
   * 选择文件之后 上传文件之前  执行的回调
   * @param file
   * @returns {Promise<*>}
   */
  const beforeUpload = async file => {

    const suffix = file.name.slice(file.name.lastIndexOf('.'))
    const filename = Date.now() + suffix
    file.key = filename // 在 getExtraData 函数中会用到, 在云存储中存储的文件的 key
    file.url = filename // 上传完成后, 用于显示内容
    const dir = ossData + file.key  // 图片的地址
    setTimeout(() => {
      props.onHandle(ossData.host + file.url)
    }, 1200)
    return file
  }

  const { accept, width } = props
  const sendApi = {
    //接受上传的文件类型
    accept: accept || '',
    //发到后台的文件参数名
    name: 'file',
    //上传的地址
    action: ossData.host,
    //上传文件改变时的状态
    onChange: onChange,
    //上传所需额外参数或返回上传额外参数的方法
    data: getExtraData,
    //上传文件之前的钩子，参数为上传的文件
    beforeUpload: beforeUpload,
    //限制上传数量
    maxCount: 1,
    //已经上传的文件列表
    //   fileList: value,
    //点击移除文件时的回调
    // onRemove: onRemove,
    //点击文件链接或预览图标时的回调
    //   onPreview: this.onPreview,
  }
  return (
    <Upload
      {...sendApi}
      listType={props.listType}
      className="avatar-uploader"
      showUploadList={false}
      onChange={onChange}
      // action="https://examination-test.oss-cn-beijing.aliyuncs.com/"
      beforeUpload={beforeUpload}
    >
      {props.children}
    </Upload>
  )
}

export default FileUpload
